<template>
    <div class="code-rule-container" style="height: 82vh; display: flex; flex-direction: column;">
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="定制标准件" name="dz"></el-tab-pane>
            <el-tab-pane label="材质" name="cz"></el-tab-pane>
            <el-tab-pane label="规格" name="gg"></el-tab-pane>
        </el-tabs>

        <div class="table-container">
            <div style="margin-bottom: 10px;">
                <el-input v-model="searchName" placeholder="按名称查询" style="width: 200px; margin-right: 10px" @keyup.enter.native="handleSearch" native-type="search"></el-input>
                <el-input v-model="searchCode" placeholder="按编码查询" style="width: 200px; margin-right: 10px" @keyup.enter.native="handleSearch" native-type="search"></el-input>
                <el-button icon="el-icon-search" circle @click="handleSearch" :loading="loading"></el-button>
                <el-button type="warning" plain @click="handleReset" :loading="loading" style="margin-left: 10px">重置</el-button>
                <el-button type="success" plain @click="handleAdd" :loading="loading">新增</el-button>
            </div>
        </div>
        <div style="flex: 1; overflow-y: auto; padding-bottom: 30px;">
            <el-table :data="dictionaries" style="width: 100%" border v-loading="loading" element-loading-text="数据加载中...">
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="name" label="名称" width="280"></el-table-column>
                <el-table-column prop="code" label="编码" sortable :sort-method="numberStringSort" width="80"></el-table-column>
                <!-- 只有在定制标准件标签页时显示权重列 -->
                <el-table-column prop="priority" label="权重" width="80" v-if="activeTab === 'dz'">
                    <template slot-scope="scope">
                        {{ scope.row.priority || 0 }}
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <el-table-column prop="username" label="创建人" width="60px"></el-table-column>
                <el-table-column prop="creatTime" label="创建时间" width="140px"></el-table-column>
                <el-table-column prop="modifierName" label="更新人" width="60px"></el-table-column>
                <el-table-column prop="updateTime" label="更新时间" width="140px"></el-table-column>
                <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                        <!-- <el-button size="small" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button> -->
                        <el-button type="primary" icon="el-icon-edit" circle plain @click="handleEdit(scope.row)" :loading="loading"></el-button>
                        <el-button type="danger" icon="el-icon-delete" circle plain @click="handleDelete(scope.row.id)" :loading="loading"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div style="margin: 10px 0;text-align: center; position: sticky; bottom: 0; background: white; z-index: 1;">
            <div style="display: flex;align-items: center;justify-content: center;">
                <div>
                    <span style="margin-left: 20px; margin-right: 10px;">排序方式:</span>
                    <el-select v-model="sortField" placeholder="选择排序字段" style="width: 120px; margin-right: 10px;">
                        <el-option label="ID" value="id"></el-option>
                        <el-option label="名称" value="name"></el-option>
                        <el-option label="编码" value="code"></el-option>
                        <el-option label="权重" value="priority"></el-option>
                        <el-option label="创建时间" value="creatTime"></el-option>
                    </el-select>
                    <el-select v-model="sortOrder" placeholder="排序顺序" style="width: 100px; margin-right: 10px;">
                        <el-option label="升序" value="asc"></el-option>
                        <el-option label="降序" value="desc"></el-option>
                    </el-select>
                </div>
                <div>
                    <span style="margin-right: 10px;">每页显示:</span>
                    <el-input-number v-model="customPageSize" :min="1" :max="100" :step="1" style="width: 120px; margin-right: 10px;"></el-input-number>
                </div>
                <el-button type="success" size="small" @click="handleRefresh" :loading="loading" style="margin-left: 20px;">确定</el-button>
                <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize" layout="total,prev,pager,next" :total="total"></el-pagination>
            </div>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="编码" prop="code">
                    <el-input v-model="formData.code"></el-input>
                </el-form-item>
                <!-- 只有在定制标准件标签页时显示权重输入框 -->
                <el-form-item label="权重" prop="priority" v-if="activeTab === 'dz'">
                    <el-input-number v-model="formData.priority" :min="0" :step="1" placeholder="请输入权重（数字越大权重越高）"></el-input-number>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="formData.description"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" :loading="loading">取消</el-button>
                <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'CodeRule',
    data() {
        return {
            activeTab: 'dz',
            dictionaries: [],
            dialogVisible: false,
            dialogTitle: '新增字典',
            formData: {
                id: null,
                name: '',
                code: '',
                description: '',
                type: '',
            },
            formRules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                code: [
                    { required: true, message: '请输入编码', trigger: 'blur' },
                ],
                priority: [
                    {
                        required: false,
                        message: '请输入有效的数字',
                        trigger: 'blur',
                        type: 'number',
                    },
                ],
            },
            pageNum: 1, // 当前页码
            pageSize: 15, // 每页数量
            customPageSize: 15, // 用户输入的每页数量
            total: 0, // 数据总条数
            loading: true, // 加载状态
            sortField: 'id', // 排序字段
            sortOrder: 'asc', // 排序顺序
            searchName: '', // 名称查询关键字
            searchCode: '', // 编码查询关键字
        }
    },
    created() {
        this.fetchDictionaries()
    },
    methods: {
        handleSearch() {
            this.pageNum = 1
            this.fetchDictionaries()
        },
        handleReset() {
            this.searchName = ''
            this.searchCode = ''
            this.fetchDictionaries()
        },
        handleCurrentChange(pageNum) {
            this.pageNum = pageNum
            this.fetchDictionaries()
        },
        // 统一刷新方法，整合分页和排序功能
        handleRefresh() {
            // 验证并更新每页数量
            if (this.customPageSize && this.customPageSize > 0) {
                this.pageSize = this.customPageSize
            } else {
                this.$message.warning('请输入有效的每页数量')
                return
            }
            
            // 验证排序字段和顺序
            if (!this.sortField || !this.sortOrder) {
                this.$message.warning('请选择排序字段和排序顺序')
                return
            }
            
            // 重置为第一页并重新加载数据
            this.pageNum = 1
            this.fetchDictionaries()
        },
        
        // 保留原有方法以确保兼容性
        updatePageSize() {
            this.handleRefresh()
        },
        
        handleSort() {
            this.handleRefresh()
        },
        handleTabClick(tab) {
            this.activeTab = tab.name
            this.fetchDictionaries()
        },
        fetchDictionaries() {
            this.loading = true
            this.$request
                .get('/dictionaries/findByPage', {
                    params: {
                        type: this.activeTab,
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        searchName: this.searchName,
                        searchCode: this.searchCode,
                        sortField: this.sortField,
                        sortOrder: this.sortOrder,
                    },
                })
                .then((res) => {
                    if (res.code === '200') {
                        if (res.data && res.data.records) {
                            this.dictionaries = res.data.records
                            this.total = res.data.total
                        } else {
                            this.$message.error('数据可能为空')
                        }
                    } else {
                        this.$message.error('获取分页数据失败：' + res.msg)
                    }
                    this.loading = false
                })
            // axios.get(`/api/dictionaries/findList?type=${this.activeTab}`)
            //   .then(response => {
            //     this.dictionaries = response.data.data; // 修正：获取响应中的data数组
            //   })
            //   .catch(error => {
            //     this.$message.error('获取字典数据失败');
            //     console.error(error);
            //   });
        },
        handleAdd() {
            this.dialogTitle = '新增字典'
            this.formData = { id: null, name: '', code: '', description: '' }
            this.dialogVisible = true
        },
        handleEdit(row) {
            this.dialogTitle = '编辑字典'
            this.formData = { ...row }
            this.dialogVisible = true
        },
        handleDelete(id) {
            this.$confirm('确定要删除这条记录吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.$request
                        .delete(
                            `/dictionaries/deleteById/${id}?type=${this.activeTab}`
                        )
                        .then((res) => {
                            if (res.code === '200') {
                                this.$message.success('删除成功')
                                this.fetchDictionaries()
                            } else {
                                this.$message.error('删除失败: ' + res.msg)
                            }
                        })
                        .catch((error) => {
                            this.$message.error('删除失败: ' + error.message)
                            console.error(error)
                        })
                })
                .catch(() => {
                    this.$message.info('已取消删除')
                })
        },
        // 自定义排序方法，将字符串类型的数字转换为数值进行比较
        numberStringSort(a, b) {
            return Number(a.code) - Number(b.code)
        },

        submitForm() {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    if (this.formData.id) {
                        // 编辑操作
                        this.$request
                            .put(
                                `/dictionaries/update/${this.formData.id}`,
                                this.formData
                            )
                            .then((res) => {
                                if (res.code === '200') {
                                    this.$message.success('更新成功')
                                    this.dialogVisible = false
                                    this.fetchDictionaries()
                                } else {
                                    this.$message.error('更新失败: ' + res.msg)
                                }
                            })
                            .catch((error) => {
                                this.$message.error(
                                    '更新失败: ' + error.message
                                )
                                console.error(error)
                            })
                    } else {
                        console.log(this.activeTab)
                        // 新增操作
                        // 确保priority字段为数字类型
                        if (
                            this.activeTab === 'dz' &&
                            this.formData.priority !== undefined
                        ) {
                            this.formData.priority =
                                parseInt(this.formData.priority) || 0
                        }
                        this.$request({
                            //有id就是编辑
                            method: this.formData.id ? 'PUT' : 'POST',
                            data: { ...this.formData, type: this.activeTab },
                            url: this.formData.id
                                ? '/dictionaries/update'
                                : '/dictionaries/save',
                        }).then((res) => {
                            if (res.code === '200') {
                                //保存成功
                                this.$message.success('保存成功')
                                this.dialogVisible = false
                                this.fetchDictionaries()
                                // this.load(this.pageNum)
                            } else {
                                this.$message.error(res.msg) //错误信息
                            }
                        })
                        // axios.post('/api/dictionaries/add', { ...this.formData, type: this.activeTab })
                        //   .then(() => {
                        //     this.$message.success('新增成功');
                        //     this.dialogVisible = false;
                        //     this.fetchDictionaries();
                        //   })
                        //   .catch(error => {
                        //     this.$message.error('新增失败');
                        //     console.error(error);
                        //   });
                    }
                } else {
                    return false
                }
            })
        },
    },
}
</script>

<style scoped>
.code-rule-container {
    padding: 10px 10px 60px; /* 底部增加60px内边距避免内容被分页遮挡 */
    max-height: 90vh;
    overflow-y: auto;
}
.table-container {
    margin-top: 5px;
}
</style>